package unl.cse.albums;

import com.google.gson.JsonObject;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AlbumAdderServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		
		String albumTitle  = request.getParameter("albumTitle");
		String bandName    = request.getParameter("bandName");  
		String albumYear   = request.getParameter("albumYear");
		String albumNumber = request.getParameter("albumNumber");


        //set CORS upfront
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");


        response.setContentType("application/json");
        PrintWriter out;
        if (albumTitle.isEmpty()||bandName.isEmpty()||albumYear.isEmpty()||albumNumber.isEmpty()){ //INPUT EMPTY

            try {
                out = response.getWriter();

                JsonObject jo = new JsonObject();
                jo.addProperty("error", "input empty!!");
                out.print(jo.toString());
                out.flush();
                return;
            } catch (IOException e) {
                throw new RuntimeException(e);

            }

        }else {// input illegal

            try {
                Integer.valueOf(albumNumber);
                Integer.valueOf(albumYear);
            } catch (NumberFormatException e) {
                try {
                    out = response.getWriter();
                    JsonObject jo = new JsonObject();
                    jo.addProperty("error", "input illegal!!");
                    out.print(jo.toString());
                    out.flush();
                    return;

                } catch (IOException e1) {
                    throw new RuntimeException(e1);
                }
            }
        }


		try {
			AlbumAdder.addAlbumToDatabase(albumTitle, bandName, albumYear, albumNumber);
			response.sendRedirect("index.html");
			
		} catch (Exception e) {
			try {
				response.sendRedirect("error.html");
			} catch (IOException e1) {
				throw new RuntimeException(e1);
			}
		}
	}
	
}
